package com.sskj.spk.ui.activity;


import android.content.res.Resources;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.SlidingTabLayout;
import com.sskj.common.adapter.MyFragmentPagerAdapter;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.widget.ViewPagerSlide;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.BibiCoinType;
import com.sskj.lib.bean.MainChangeTabBean;
import com.sskj.lib.bean.StockCoinBean;
import com.sskj.spk.R;
import com.sskj.spk.bean.Currency;
import com.sskj.spk.presenter.MarketNewActivityPresenter;
import com.sskj.spk.ui.fragment.ChartFragment;
import com.sskj.spk.ui.fragment.SummaryFragment;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Flowable;

/**
 * DESC: (类描述) 币的行情信息  K线图
 * Created by hqf on 2018/11/17 10:04
 * updateName:(修改人名称)
 * updateTime:(修改时间)
 * updateDesc:(修改内容)
 */
@Route(path = RConfig.APP_MARKET_NEW)//K线图界面
public class MarketNewActivity extends BaseActivity<MarketNewActivityPresenter> {
    @BindView(R.id.priceNow)
    TextView mPriceNow; // 当前价格
    @BindView(R.id.changeRate)
    TextView mChangeRate; // 当前价格  右侧  百分比
    @BindView(R.id.highText)
    TextView mHighText;
    @BindView(R.id.highPrice)
    TextView mHighPrice; // 高 价格
    @BindView(R.id.lowText)
    TextView mLowText;
    @BindView(R.id.lowPrice)
    TextView mLowPrice; // 低  价格
//    @BindView(R.id.tablayout)
//    TabLayout mTablayout;
    //    @BindView(R.id.market_viewpager)
//    ViewPagerSlide mMarketViewpager;
    @BindView(R.id.slidingTabLayout)
    SlidingTabLayout slidingTabLayout;
    @BindView(R.id.chartViewPager)
    ViewPager chartViewPager;
    @BindView(R.id.appTvTitle)
    TextView appTvTitle;
    @BindView(R.id.market_info)
    LinearLayout marketInfo;
    @BindView(R.id.marketBuy)
    TextView mMarketBuy;  // 买入
    @BindView(R.id.marketSale)
    TextView mMarketSale;  // 卖出
    @BindView(R.id.tvRMB)
    TextView tvRMB;
    @BindView(R.id.frameLayout)
    FrameLayout frameLayout;

    /**
     * 0 五大币 1 交易币
     */
    public Currency type;

    @Autowired
    public String code;

    private List<Fragment> mFragments = new ArrayList();
    private MyFragmentPagerAdapter mPagerAdapter;
    private List<Fragment> fragmentList = new ArrayList<>();
    String[] goodsType = {"minute", "minute", "minute5", "minute15", "minute30", "minute60", "day"};


    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_market_new;
    }

    @Override
    public MarketNewActivityPresenter getPresenter() {
        return new MarketNewActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        appTvTitle.setText(code.toUpperCase());
        List<String> downTitles = new ArrayList<>();
        downTitles.add("简介");
        mFragments.add(SummaryFragment.newInstance(code));
//        mPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), downTitles, mFragments);

//        mMarketViewpager.setAdapter(mPagerAdapter);
//        mMarketViewpager.resetHeight(0);
//        mTablayout.setupWithViewPager(mMarketViewpager);
//        mTablayout.post(() -> setIndicator(mTablayout, 60, 60));
        initTab();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.frameLayout, mFragments.get(0));
        fragmentTransaction.show(mFragments.get(0));
        fragmentTransaction.commitAllowingStateLoss();

        mMarketSale.setVisibility(View.GONE);


    }

    @Override
    protected void initData() {
        mPresenter.getNewInfo(code);

//        //卖出
//        ClickUtil.click(mMarketSale, () -> {
//
//            if (BaseApplication.mainActivity != null) {
//                BaseApplication.mainActivity.setTabSelection(2);
//                BaseApplication.mainActivity.bottomNavigationBar.selectTab(2);
//            }
//            RxBus.getDefault().post(new LevelCoinType(code, true));
//            finish();
//
//        });
        //买入
        ClickUtil.click(mMarketBuy, () -> {
            RxBus.getDefault().post(new MainChangeTabBean(1));
            RxBus.getDefault().post(new BibiCoinType(code, false));
            finish();
        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(StockCoinBean stock) {
        if (stock.getCode().equals(code)) {
            if (Double.valueOf(stock.getChange()) >= 0) {
                mChangeRate.setTextColor(getResources().getColor(R.color.app_green));
                mPriceNow.setTextColor(getResources().getColor(R.color.app_green));
                mMarketBuy.setBackground(ContextCompat.getDrawable(App.INSTANCE, R.drawable.app_shape_green_rect));
            } else {
                mChangeRate.setTextColor(getResources().getColor(R.color.app_red));
                mPriceNow.setTextColor(getResources().getColor(R.color.app_red));
                mMarketBuy.setBackground(ContextCompat.getDrawable(App.INSTANCE, R.drawable.app_shape_red_rect));
            }
            tvRMB.setText("≈ ￥ " + stock.getCnyPrice());
            mChangeRate.setText(stock.getChangeRate());
            mHighPrice.setText(stock.getHigh());
            mLowPrice.setText(stock.getLow());
            mPriceNow.setText(stock.getPrice());
        }
    }

    private void initTab() {

        List<String> chartTitles = new ArrayList<>();
        chartTitles.add("分时");
        chartTitles.add("1M");
        chartTitles.add("5M");
        chartTitles.add("15M");
        chartTitles.add("30M");
        chartTitles.add("1H");
        chartTitles.add("日线");
        Flowable.rangeLong(0, 7)
                .subscribe(index -> fragmentList.add(ChartFragment.newInstance(code, goodsType[index.intValue()], index != 0)));
        chartViewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), chartTitles, fragmentList));
        slidingTabLayout.setViewPager(chartViewPager);
        slidingTabLayout.setCurrentTab(3);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    public static void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }
}
